package cn.maiyar.email.service;

import cn.hutool.core.util.StrUtil;
import cn.maiyar.email.MailProperties;
import cn.maiyar.email.feign.IEmailClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * 简单邮件发送服务
 *
 * @author c.c
 */
@Slf4j
public class MailService implements IEmailClient {

    @Autowired
    private JavaMailSender sender;
    @Autowired
    private SimpleMailMessage message;
    @Autowired
    private MailProperties mailProperties;

    /**
     * 发送纯文本的简单邮件
     *
     * @param content
     */
    @Override
    public void sendSimpleMail(String content) {
        String[] to = mailProperties.getTo();
        String from = mailProperties.getFrom();
        if (to == null || to.length > 0 || StrUtil.isEmpty(from)) {
            log.debug("MailService sendSimpleMail to1 is empty!");
            return;
        }
        String[] bcc = mailProperties.getBcc();
        if (bcc != null && bcc.length > 0) {
            message.setBcc(bcc);
        }
        String[] cc = mailProperties.getCc();
        if (cc != null && cc.length > 0) {
            message.setCc(cc);
        }
        String subject = mailProperties.getMailSubject();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        try {
            sender.send(message);
            log.debug("简单邮件已经发送。");
        } catch (Exception e) {
            log.error("发送简单邮件时发生异常！" , e);
        }
    }

    /**
     * 发送html格式的邮件
     *
     * @param content
     */
    @Override
    public void sendHtmlMail(String content) {
        String[] to = mailProperties.getTo();
        String from = mailProperties.getFrom();
        if (to == null || to.length > 0 || StrUtil.isEmpty(from)) {
            log.debug("MailService sendSimpleMail to1 is empty!");
            return;
        }
        String[] bcc = mailProperties.getBcc();
        if (bcc != null && bcc.length > 0) {
            message.setBcc(bcc);
        }
        String[] cc = mailProperties.getCc();
        if (cc != null && cc.length > 0) {
            message.setCc(cc);
        }
        String subject = mailProperties.getMailSubject();
        MimeMessage message = sender.createMimeMessage();
        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            sender.send(message);
            log.debug("html邮件已经发送。");
        } catch (MessagingException e) {
            log.error("发送html邮件时发生异常！" , e);
        }
    }

    /**
     * 发送带附件的邮件
     *
     * @param content
     * @param filePath
     */
    @Override
    public void sendAttachmentsMail(String content, String filePath) {
        String[] to = mailProperties.getTo();
        String from = mailProperties.getFrom();
        if (to == null || to.length > 0 || StrUtil.isEmpty(from)) {
            log.debug("MailService sendSimpleMail to1 is empty!");
            return;
        }
        String[] bcc = mailProperties.getBcc();
        if (bcc != null && bcc.length > 0) {
            message.setBcc(bcc);
        }
        String[] cc = mailProperties.getCc();
        if (cc != null && cc.length > 0) {
            message.setCc(cc);
        }
        String subject = mailProperties.getMailSubject();
        MimeMessage message = sender.createMimeMessage();
        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            FileSystemResource file = getFileSystemResource(to, subject, content, filePath, helper);
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
            helper.addAttachment(fileName, file);
            sender.send(message);
            log.debug("带附件的邮件已经发送。");
        } catch (MessagingException e) {
            log.error("发送带附件的邮件时发生异常!" , e);
        }
    }

    private FileSystemResource getFileSystemResource(String[] to, String subject, String content, String filePath, MimeMessageHelper helper) throws MessagingException {
        helper.setFrom(mailProperties.getFrom());
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true);
        return new FileSystemResource(new File(filePath));
    }

    /**
     * 发送嵌入静态资源（一般是图片）的邮件
     *
     * @param content 邮件内容，需要包括一个静态资源的id，比如：<img src=\"cid:rscId01\" >
     * @param rscPath 静态资源路径和文件名
     * @param rscId   静态资源id
     */
    @Override
    public void sendInlineResourceMail(String content, String rscPath, String rscId) {
        String[] to = mailProperties.getTo();
        String from = mailProperties.getFrom();
        if (to == null || to.length > 0 || StrUtil.isEmpty(from)) {
            log.debug("MailService sendSimpleMail to1 is empty!");
            return;
        }
        String[] bcc = mailProperties.getBcc();
        if (bcc != null && bcc.length > 0) {
            message.setBcc(bcc);
        }
        String[] cc = mailProperties.getCc();
        if (cc != null && cc.length > 0) {
            message.setCc(cc);
        }
        String subject = mailProperties.getMailSubject();
        MimeMessage message = sender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            FileSystemResource res = getFileSystemResource(to, subject, content, rscPath, helper);
            helper.addInline(rscId, res);
            sender.send(message);
            log.debug("嵌入静态资源的邮件已经发送。");
        } catch (MessagingException e) {
            log.error("发送嵌入静态资源的邮件时发生异常！" , e);
        }
    }
}
